package com.namuan.jp_stock.activity;



import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;


import com.namuan.jp_stock.object.ShotActivity;
import com.namuan.jp_stock.util.ActivityItemAdapter;
import com.namuan.jp_stock.util.AsyncJustplaceRunner;
import com.namuan.jp_stock.util.BaseRequestListener;
import com.namuan.jp_stock.util.Justplace;
import com.namuan.jp_stock.util.JustplaceError;
import com.namuan.jp_stock.util.ObjUtils;
import com.namuan.jp_stock.util.SessionStore;
import com.namuan.jp_stock.util.Util;
import com.namuan.jp_stock.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity implements OnClickListener, OnItemClickListener, OnScrollListener {
    /** Called when the activity is first created. */
	
	private AsyncJustplaceRunner mAsyncRunner;
	private Justplace mJutplace;
	
	
	private Context mContext;
	private ArrayList<ShotActivity> activityItems;
	private ListView activityListView;
	private ActivityItemAdapter aa;
	
	
	private TextView userHeaderNickname;
	
	private ImageView navBtn1;
	private ImageView navBtn2;
	private ImageView navBtn3;
	private ImageView navBtn4;
	private String lastActivityid;
	private boolean lockListView;
	private Boolean loadingMore = false;
	private Boolean isTwoClickBack = false;
	private Boolean isfirst;	
	private TextView tvEndOfList = null;
	private View dummyView;
	private View footerView;
	private View text_end_of_list = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        lockListView = false;
		isfirst = true;
		LoginActivity.activityList.add(this);
		// ActivityStart();
		mContext = this;
		setContentView(R.layout.main);
		userHeaderNickname = (TextView) findViewById(R.id.userHeaderNickname);
		ImageButton headerWriteBtn = (ImageButton) findViewById(R.id.headerWriteBtn);
		ImageButton headerLoginBtn = (ImageButton) findViewById(R.id.headerLoginBtn);
		
      
		activityListView = (ListView)findViewById(R.id.activityListView);
		navBtn1 = (ImageView)findViewById(R.id.navBtn1);
		navBtn2 = (ImageView)findViewById(R.id.navBtn2);
		navBtn3 = (ImageView)findViewById(R.id.navBtn3);
		navBtn4 = (ImageView)findViewById(R.id.navBtn4);
		
		userHeaderNickname.setOnClickListener(this);
		headerWriteBtn.setOnClickListener(this);
		
		navBtn1.setOnClickListener(this);
		navBtn2.setOnClickListener(this);
		navBtn3.setOnClickListener(this);
		navBtn4.setOnClickListener(this);
		footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
		dummyView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dummy, null, false);
		
		activityListView.addFooterView(dummyView);
		activityListView.setOnScrollListener(this);
		activityItems = new ArrayList<ShotActivity>();
		aa = new ActivityItemAdapter(this, R.layout.activity_list_row, activityItems);
		
		activityListView.setAdapter(aa);
		aa.setNotifyOnChange(true);
		
		activityListView.setOnItemClickListener(this);
        
        mJutplace = new Justplace();
        mJutplace.setmSession("A03C5AF941BECDD98F5F5903354BFB6C");
		SessionStore.restore(mJutplace, this);
		
		mJutplace.setHeader(userHeaderNickname);
		if(userHeaderNickname.toString() != null) {
			headerLoginBtn.setVisibility(View.GONE);	
		}
		mAsyncRunner = new AsyncJustplaceRunner(mJutplace);
		init();
		
		
    }
    private void init(){
    	Bundle params = new Bundle();
    	/**/
    	mAsyncRunner.request("loadallactivitys.do", params, "GET",
                 new LoadActivityRequestListener(), null);
                 /***/
    	
    	/******** 임시 데이터 삽입 *********
    	for(int i = 0 ; i < 30 ; i ++) {
    		ShotActivity temp = null;
    		temp.setActivitypw(true);
    		temp.setComment("test comment");
    		temp.setRecommendation(3);
    		temp.setStockname("코스피");
    		temp.setTimestamp("2011-11-04 12:15:10");
    		temp.setTrackbackcount(3);
    		temp.setUsernickname("parkth");
    		activityItems.add(temp);
    	}
    	aa.notifyDataSetChanged();
    	/*********************/
    }
	class CntTimer extends CountDownTimer {
		public CntTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
			isTwoClickBack = true;
		}

		@Override
		public void onFinish() {
			isTwoClickBack = false;
		}

		@Override
		public void onTick(long millisUntilFinished) {
			// TODO Auto-generated method stub
			//Log.i("Test", " isTwoClickBack " + isTwoClickBack);
		}

	}
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (event.getAction() == KeyEvent.ACTION_DOWN) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				if (!isTwoClickBack) {
					Toast.makeText(this, "'뒤로'버튼을 한번 더 클릭하시면 종료됩니다.",
							Toast.LENGTH_SHORT).show();
					CntTimer timer = new CntTimer(2000, 1);
					timer.start();
				} else {
					finish();
					return true;
				}

			}
		}
		return false;
	}

	public class LoadActivityRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			Log.d("Justplace-Main", "Response: " + response.toString());
			try {
				activityItems.clear();
				Log.d("Justplace-Main", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				final ArrayList<ShotActivity> activitys = ObjUtils.jsonToShotActivityList(json.getJSONArray("activityList"));
				lastActivityid = activitys.get(activitys.size() - 1).getActivityid();
				for (ShotActivity act : activitys) {
					activityItems.add(act);
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						/*
						while(activityItems.size() < 5){
						}
						*/
						aa.notifyDataSetChanged();
						isfirst = false;
						if(activityItems.size() == 30){
							loadingMore = true;
							activityListView.addFooterView(footerView);
						} else {
							loadingMore = false;		
						}
					}
				});
			} catch (JSONException e) {
				Log.w("Justplace-Main", "JSON Error in response");
			} catch (JustplaceError e) {
				Log.w("Justplace-Main", "Justplace Error: " + e.getMessage());
			}
		}
    }
    public class LoadMoreActivityRequestListener extends BaseRequestListener {
        public void onComplete(final String response, final Object state) {
        	 Log.d("Justplace-LoadMore", "Response: " + response.toString());
            try {
                Log.d("Justplace-LoadMore", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                ArrayList<ShotActivity> activitys =ObjUtils.jsonToShotActivityList(json.getJSONArray("hashMapList"));
                lastActivityid = activitys.get(activitys.size()-1).getActivityid();
                if(activitys.size()<15){
					loadingMore=false;
                	Log.d("nomore","nomore");                	
                	runOnUiThread(new Runnable() {
						@Override
						public void run() {
							activityListView.removeFooterView(footerView);
							//footerView.setVisibility(View.GONE);
							if(text_end_of_list == null) {
								text_end_of_list = ((LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.text_end_of_list, null, false);
								activityListView.addFooterView(text_end_of_list);
							}
						}
					});
						
                }
                for(ShotActivity act:activitys){
                	activityItems.add(act);
                }
               runOnUiThread(new Runnable(){
				@Override
				public void run() {
					 aa.notifyDataSetChanged();
					 lockListView = false;
				}
            	   
               });
               
            } catch (JSONException e) {
                Log.w("Justplace-Main", "JSON Error in response");
            } catch (JustplaceError e) {
                Log.w("Justplace-Main", "Justplace Error: " + e.getMessage());
            }
        }
    }

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		int lastInScreen = firstVisibleItem + visibleItemCount;				
		//int count = totalItemCount - visibleItemCount;
		Log.d("START", "START222");
		//is the bottom item visible & not loading more already ? Load more !
		if((!isfirst && lastInScreen == totalItemCount) &&  !lockListView && loadingMore){
		// if(firstVisibleItem >= count && totalItemCount != 0 && loadingMore == true) {
        	lockListView = true;
			Log.d("START", "START");
			Bundle params = new Bundle();
	        params.putString("activityid", lastActivityid);
	        mAsyncRunner.request("loadmoreactivitys.do", params, "GET",
	                 new LoadMoreActivityRequestListener(), null);
		}
	}
	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		ShotActivity  Item = (ShotActivity)aa.getItem(arg2);
		String activityid = Item.getActivityid();
		/* 보완 - myprofile or userprofile */
		Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
		intent.putExtra("activityid", activityid);
		startActivity(intent);
		overridePendingTransition(R.anim.fade, R.anim.hold);
	}
	@Override
	public void onClick(View v) {
		switch(v.getId())
		{
			case R.id.headerLoginBtn:
				Intent login_intent = new Intent(this, LoginActivity.class);
			    this.startActivity(login_intent);
			    overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
			case R.id.headerWriteBtn:
				Intent Insert_intent = new Intent(this, AddActivity.class);
			    this.startActivity(Insert_intent);
			    overridePendingTransition(R.anim.fade, R.anim.hold);
				break;
				
			case R.id.userHeaderNickname:
				Intent userHeaderIdintent = new Intent(this, MyProfileActivity.class);
			    this.startActivity(userHeaderIdintent);
			    overridePendingTransition(R.anim.fade, R.anim.hold);
				break;
			case R.id.navBtn1://main
				aa.clear();
				aa.notifyDataSetChanged();
				if(text_end_of_list != null) {
					activityListView.removeFooterView(text_end_of_list);
					text_end_of_list = null;
				}
				if(footerView.getParent() != null) {
					activityListView.removeFooterView(footerView);
				}
				Bundle params = new Bundle();
				mAsyncRunner.request("loadallactivitys.do", params, "GET", new LoadActivityRequestListener(), null);
				break;
				
			case R.id.navBtn2:// stock line
			/*
			Intent navBtn2intent = new Intent(this, StockActivity.class);
			this.startActivity(navBtn2intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);*/
			//finish();
			break;
			
		case R.id.navBtn3:// friends line
			/*
			Intent navBtn3intent = new Intent(this, FriendsActivity.class);
			this.startActivity(navBtn3intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);*/
			//finish();
			break;
			
		case R.id.navBtn4:// profile
			/*
			Intent navBtn4intent = new Intent(this, MyProfileActivity.class);
			this.startActivity(navBtn4intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			*/
			//finish();
			break;
				
		}
		
	}
}